//
//  SortStepView.m
//  project
//
//  Created by 黄建华 on 2019/1/8.
//  Copyright © 2019年 黄建华. All rights reserved.
//

#import "SortStepView.h"

@implementation SortStepView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self performSelector:@selector(createChartView) withObject:nil afterDelay:IOSINITWAITTIME];
    }
    return self;
}

- (void)createChartView {
    self.backgroundColor = [UIColor whiteColor];
}

// 更新数据
- (void)UpdateViewWithSortStep
{
    [self loadBackgroundLayer];
    
    //数据加载
    NSMutableArray *array  = [NSMutableArray array];
    for (int i =0; i <7; i++) {
        [array addObject:@"0"];
    }
    
    NSMutableArray *labelArray1 =  [NSMutableArray arrayWithArray:@[@"0",@"3001",@"6001",@"9001",@"12001",@"15001",@"18001"]];
    NSMutableArray *labelArray3 = [NSMutableArray arrayWithArray:@[@"3000",@"6000",@"9000",@"12000",@"15000",@"18000",@"∞"]];
    NSMutableArray *valueArray = [NSMutableArray array];
    SortModel *model = [SortModel getSortModelFromDBWithDayString:[[NSDate date]dateToDayString]];
    NSInteger currentStep = SN_PublicClass.todaySport.step;
    int currentIndex = 0;
    if (model.stepSort.count >0) {
        for (int k = 0; k <array.count; k++) {
            NSDictionary *dic = [model.stepSort objectAtIndex:k];
            int value = [dic[@"value"]intValue];
            [array replaceObjectAtIndex:k withObject:StrByInt(value)];
            int left = [dic[@"left"]intValue];
            int right = [dic[@"right"]intValue];
            if (currentStep > left) {
                currentIndex = k;
            }
            [valueArray addObject:StrByInt(value)];
            [labelArray1 replaceObjectAtIndex:k withObject:StrByInt(left)];
            [labelArray3 replaceObjectAtIndex:k withObject:StrByInt(right)];
            if (k == array.count-1) {
                if (right == 0) {
                    [labelArray3 replaceObjectAtIndex:k withObject:@"∞"];
                }
            }
        }
    }

    
    _selectDateLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(5, 10, 200, 20)];
    _selectDateLabel.textAlignment = NSTextAlignmentLeft;
    _selectDateLabel.textColor     = SNCOLORBLACK;
    _selectDateLabel.font          = SNSFONT(14.0);
//    [_chartView addSubview:_selectDateLabel];
    
    UIView *lineGray = [[UIView alloc] init];
    lineGray.backgroundColor = SNCOLORWITHHEX(0xd7d8d9);
    lineGray.frame           = SNFRAME(5, self.height - 40, HHHWIDTH - 10, 1);
    [_chartView addSubview:lineGray];
    
    _valueLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0,lineGray.bottom + 38 ,self.width, 20)];
    _valueLabel.adjustsFontSizeToFitWidth = YES;
    _valueLabel.textAlignment = NSTextAlignmentCenter;
    _valueLabel.textColor     = SNCOLORBLACK;
    _valueLabel.font          = SNFONT(14.0);
    [_chartView addSubview:_valueLabel];

    _unitLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0,_valueLabel.bottom - 5, self.width, 30)];
    _unitLabel.textColor     = SNCOLORGRAY;
    _unitLabel.font          = SNSFONT(10.5);
    _unitLabel.textAlignment = NSTextAlignmentCenter;
    _unitLabel.numberOfLines = 2;
    [_chartView addSubview:_unitLabel];
    
    
    NSInteger maxValue = [self max:array];
    NSInteger minValue = [self min:array];
    
    float   Origin_x      = 10;
    CGFloat Origin_height = self.height - 40;
    CGFloat offsetY       = FitScreenNumber(40, 40, 40, 40, 40);
    
    for (int i = 0; i < array.count; i++) {
        CGFloat value = [[array objectAtIndex:i] floatValue];
        if (value > maxValue) {
            value = maxValue;
        }
        
        CGFloat height = 0;
        CGFloat h      = (self.height - (25 + 30 + offsetY)) * (value / maxValue);
        if (isnan(h)) {
            height = 0;
        } else {
            height = h;
        }
        static int total = 0;
        total = total + value;
        
        CGFloat chartWidth = 0;
        CGFloat chartSpace = 0;
        Origin_x   = 20;
        chartWidth = 8;
        chartSpace = (self.width - Origin_x *2)/array.count + 5;
        
        CGPoint point01 = CGPointMake(i * chartSpace + Origin_x, Origin_height-height);
        CGPoint point02 = CGPointMake((i) * chartSpace + Origin_x +chartWidth, Origin_height-height);
        
        UIBezierPath *fill = [UIBezierPath bezierPath];
        [fill moveToPoint:point01];
        [fill addLineToPoint:point02];
        [fill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [fill addLineToPoint:CGPointMake(point01.x, Origin_height)];
        
        // 填充区域
        CAShapeLayer *fillLayer = [CAShapeLayer layer];
        fillLayer.frame       = self.bounds;
        fillLayer.bounds      = self.bounds;
        fillLayer.path        = fill.CGPath;
        fillLayer.strokeColor = SNCOLORBLACK.CGColor;
        fillLayer.fillColor   = SNCOLORBLACK.CGColor;
        fillLayer.lineWidth   = 0.0;
        fillLayer.lineJoin    = kCALineJoinRound;
        [_backGroundLayer addSublayer:fillLayer];
        
        UIBezierPath *noFill = [UIBezierPath bezierPath];
        [noFill moveToPoint:CGPointMake(point01.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point01.x, Origin_height)];
        
        // 填充区域过渡动画
        CABasicAnimation *fillAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
        fillAnimation.duration       = SNACTIONTIME;
        fillAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        fillAnimation.fillMode       = kCAFillModeForwards;
        fillAnimation.fromValue      = (id)noFill.CGPath;
        fillAnimation.toValue        = (id)fill.CGPath;
        [fillLayer addAnimation:fillAnimation forKey:@"path"];
        
        //圆角
        UIView *view = [[UIView alloc] init];
        view.frame           = SNFRAME(point01.x, point01.y + height, chartWidth, height==0?0:5);
        view.backgroundColor = SNCOLORBLACK;
        [_chartView addSubview:view];
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius  = chartWidth/2;
        view.alpha               = 1;
        
        UIImageView *finishImageView = [[UIImageView alloc] init];
        finishImageView.frame  = SNFRAME(point01.x - 11 + chartWidth/2, point01.y - 20 - chartWidth -5, 22, 22);
        finishImageView.image  = SN_USER.headImage;
        finishImageView.layer.cornerRadius = 11.0;
        finishImageView.layer.masksToBounds = YES;
        if (i == currentIndex) {
            [_chartView addSubview:finishImageView];
        }
        if (currentStep == 0) {
            finishImageView.hidden = YES;
        }
        else
        {
            finishImageView.hidden = NO;
        }
        
        dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SNACTIONTIME * NSEC_PER_SEC));
        void            (^task)() = ^{
            view.alpha = 1.0;
            view.frame = SNFRAME(point01.x, point01.y - 2, chartWidth, 5);
        };
        // 经过多少纳秒，由主队列调度任务异步执行
        dispatch_after(when, dispatch_get_main_queue(), task);
        NSMutableArray *labelArray = [NSMutableArray array];

        for (int i = 0; i <array.count; i++) {
            NSString *s1 = [labelArray1 objectAtIndex:i];
            NSString *s2 = @"|";
            NSString *s3 = [labelArray3 objectAtIndex:i];
            NSString *string = [NSString stringWithFormat:@"%@\n%@\n%@",s1,s2,s3];
            [labelArray addObject:string];
            
        }
            SNCustomLabel *label     = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0,lineGray.bottom +10, 100, 40)];
            label.center        = CGPointMake(view.center.x,lineGray.bottom + 20);
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor     = SNCOLORGRAY;
            label.font          = SNSFONT(9.0);
            label.text          = [labelArray objectAtIndex:i];
            label.numberOfLines = 3;
            [_chartView addSubview:label];
    }

    
    int more = 0;
    for (int k = 0; k <currentIndex; k++) {
        more += [[valueArray objectAtIndex:k]intValue];
    }

    int sum = [[valueArray valueForKeyPath:@"@sum.floatValue"] intValue];
    
    //当前步数区间
    int currentStepS = [[labelArray3 objectAtIndex:currentIndex]intValue];
    
    float vvv = 1.0 *more/sum *100;
    float currentVVV = 1.0*currentStep / currentStepS *100;
    
    float v = vvv;
    if (currentIndex == 0) {
        v = 1.0;
    }
    if (currentIndex == valueArray.count -1) {
        v = 99.0;
    }
    _valueLabel.text = [NSString stringWithFormat:@"%@ %.0f%%% @",SN_Text(@"你超过了"),v,SN_Text(@"用户")];
    NSString *stepInfo = SN_Text(@"自行车骑行超过1小时的距离");
    if (currentStep >=0 && currentStep <3000) {
        stepInfo = SN_Text(@"普通用户在健身房热身的运动量");
    }
    if (currentStep >=3001 && currentStep <6000) {
         stepInfo = SN_Text(@"换成高度相当于登上了富士山");
    }
    if (currentStep >=6000 && currentStep <9000) {
         stepInfo = SN_Text(@"WHO推荐的成年人每日完成的步数目标");
    }
    if (currentStep >=9001 && currentStep <12000) {
         stepInfo = SN_Text(@"你为地球减少了约805g二氧化碳排放");
    }
    if (currentStep >=12000 && currentStep <15000) {
         stepInfo = SN_Text(@"你完成了从卢浮宫到巴黎铁塔的距离");
    }
    if (currentStep >=15001 && currentStep <18000) {
         stepInfo = SN_Text(@"相当于操场跑了30圈");
    }
    if (currentStep >=18000) {
         stepInfo = SN_Text(@"自行车骑行超过1小时的距离");
    }
    _unitLabel.text =  stepInfo;
}

- (void)loadBackgroundLayer {
    if (_chartView) {
        [_chartView removeFromSuperview];
        _chartView = nil;
    }
    
    _chartView                 = [[UIView alloc] init];
    _chartView.backgroundColor = [UIColor whiteColor];
    _chartView.frame           = CGRectMake(0, 0, self.width, self.height);
    [self addSubview:_chartView];
    
    if (_backGroundLayer) {
        [_backGroundLayer removeFromSuperlayer];
        _backGroundLayer = nil;
    }
    _backGroundLayer                 = [CALayer layer];
    _backGroundLayer.backgroundColor = [UIColor clearColor].CGColor;
    _backGroundLayer.bounds          = CGRectMake(0, 0, self.width, self.height);
    _backGroundLayer.position        = CGPointMake(self.center.x, self.height / 2);
    [_chartView.layer addSublayer:_backGroundLayer];
}

- (NSInteger)max:(NSArray *)Array {
    if (Array.count == 0) {
        return 0;
    }
    
    NSInteger max = [[Array objectAtIndex:0] integerValue];
    
    for (int i = 0; i < Array.count; i++) {
        if ([[Array objectAtIndex:i] integerValue] > max) {
            max = [[Array objectAtIndex:i] integerValue];
        }
    }
    
    return max;
}

- (NSInteger)min:(NSArray *)Array {
    if (Array.count == 0) {
        return 0;
    }
    
    NSInteger min = [[Array objectAtIndex:0] integerValue];
    
    for (int i = 0; i < Array.count; i++) {
        if ([[Array objectAtIndex:i] integerValue] < min) {
            min = [[Array objectAtIndex:i] integerValue];
        }
    }
    return min;
}

@end

